package com.light.netty.server.handler;

import com.light.netty.server.security.MessageProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

// 自定义业务处理器（线程池隔离）
public class HttpBusinessHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) {
        // 直接获取请求体内容（ByteBuf 类型）
        ByteBuf content = req.content();

        // 将 ByteBuf 转换为 String（按需处理）
        String msg = content.toString(CharsetUtil.UTF_8);
        System.out.println("收到客户端消息: " + msg);


        String responseMsg = "receive ack:" + msg;
        ByteBuf reponseContent = Unpooled.copiedBuffer(responseMsg.getBytes());
        // 构建响应
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                reponseContent
        );
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, reponseContent.readableBytes()); // 添加Content-Length头
        ctx.writeAndFlush(response).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("HTTP Server Message sent successfully");
            } else {
                System.err.println("HTTP Server Failed to send message: " + future.cause());
            }
        });
    }

    private void processMessage(MessageProtocol msg) throws InterruptedException {
        Thread.sleep(1000); // 模拟耗时操作
        System.out.println("服务端业务处理..........");
    }
}